package com.java.fork;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.concurrent.RecursiveAction;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import com.java.gui.MainFrame;

public class CopyFiles extends RecursiveAction {

	public static final int FILE_COUNT_THRESHOLD = 2;
	private String[] mSource;
	private int mStart;
	private int mLength;
	private String mDestination;
	private String area = "";
	private Thread textAreaThread;
	private Thread progressBarThread;
	private boolean checkError = false;
	private ArrayList<File> FileCopyed = new ArrayList<File>();
	private int valueProgress;
	private int variable_progress = 1;

	public CopyFiles(String[] src, int start, int length, String dst) {
		mSource = src;
		mStart = start;
		mLength = length;
		mDestination = dst;
	}

	@Override
	protected synchronized void compute() {
		if (mLength < FILE_COUNT_THRESHOLD) {
			computeDirectly();
			return;
		}

		int split = mLength / 2;

		invokeAll(new CopyFiles(mSource, mStart, split, mDestination),
				new CopyFiles(mSource, mStart + split, mLength - split,
						mDestination));
	}

	private synchronized void computeDirectly() {
		System.out.println(Thread.currentThread() + " copy: " + mStart + " to "
				+ mLength);
		valueProgress = 100 / mSource.length;
		for (int i = 0; i < mSource.length; i++) {
			variable_progress++;
			if (MainFrame.checkCancel == true) {
				Thread.currentThread().interrupt();
				for (int j = 0; j < FileCopyed.size(); j++) {
					FileCopyed.get(j).delete();
				}
				MainFrame.progressBar.setValue(0);
				break;
			} else {
				File fileSource = new File(mSource[i]);
				File fileDest = new File(mDestination);
				try {
					if (fileDest.isFile()) {
						FileUtils.copyFile(fileSource, fileDest);
					} else {
						FileUtils.copyFileToDirectory(fileSource, fileDest);
					}
					File f = new File(mDestination + "\\"
							+ fileSource.getName());
					FileCopyed.add(f);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					checkError = true;
					StringWriter errors = new StringWriter();
					e.printStackTrace(new PrintWriter(errors));
					area += errors.toString().substring(0, 200) + "\n";
				}
				if (checkError == false) {
					area += "Copy file " + fileSource.getName() + " To "
							+ fileDest.getName() + "\n";
				}
				textAreaThread = new Thread() {
					public synchronized void run() {
						MainFrame.textArea.setText(area);
					};
				};
				textAreaThread.start();

				progressBarThread = new Thread() {
					public synchronized void run() {
						MainFrame.progressBar.setValue(valueProgress
								* variable_progress);
					};
				};
				progressBarThread.start();
				checkError = false;
			}
		}
	}

}
